#!/usr/bin/perl

use strict;
use CGI;
use YAML::Syck;
use JSON;
use Switch;
require 'config.pl';

my $cgi = new CGI;

print "Content-type: text/html\n\n";


if ($cgi->param()) {

    unless($cgi->param('mode')) {
        print "Direct access not permitted. Exiting.\n";
        exit 0;
    }

    my $mode = $cgi->param('mode');

    switch  ($mode) {
        case "2do"      { print_2dos(); }
        case "finished" { print_finished(); }
        case "current"  { print_active(); }
        case "rlsnfo"   { print_rls_nfo($cgi->param('rls')); }
        else            { print "Unknown mode \"$mode\". Exiting."; exit 0;}
    }
}
else {
    # es wurde noch nicht abgeschickt, also muss ich es anzeigen
    print "Required POST-Variables are missing. Exiting.\n";
    exit 0;
}


sub print_2dos {

    my $json = new JSON;
    my $todos = {};
    my $rls = {};

    $todos = LoadFile($::rsspreader_yaml_2do_file);

    while (my ($key, $value) = each(%{$todos} )) {
		push(@{$rls->{'2dos'}}, $key);
	}

    print $json->encode($rls);

}

sub print_finished {

    my $json = new JSON;
    my $finished = {};
    my $rls = {};

    $finished = LoadFile($::rsspreader_yaml_done_file);

    while (my ($key, $value) = each(%{$finished} )) {
		push(@{$rls->{'finished'}}, $key);
	}

    print $json->encode($rls);
}

sub print_active {

    my $json = new JSON;
    my $rls_nfo = {};
     
    if(-e $::rsspreader_yaml_current_file) 
    {
        $rls_nfo = LoadFile($::rsspreader_yaml_rls_nfo_dir."/".$rls.".yaml");
        print $json->encode($rls_nfo);
    }    
    else
    {
        print "Currently there is no download in process. Exiting.\n";
    }
}

sub print_rls_nfo {

    my $json = new JSON;
    my $rls = shift;
    my $rls_nfo = {};
    
    if(-e $::rsspreader_yaml_rls_nfo_dir."/".$rls.".yaml") 
    {
        $rls_nfo = LoadFile($::rsspreader_yaml_rls_nfo_dir."/".$rls.".yaml");
        print $json->encode($rls_nfo);
    }
    else
    {
        print "No RLS Info file found. Exiting.\n";
    }
}
